import request from './request.js'

/**
 * 歌词获取和解析
 */

/**
 * 获取歌词
 * @param {*} url 
 */
function get(url) {
  return request.get(url).then(function (response) {
    return Promise.resolve(parse(response))
  })
}

/**
 * 解析歌词 https://github.com/TivonJJ/html5-music-player
 * @param {*} lrc 
 */
function parse(lrc) {
  if (lrc === '') return '';
  let lyrics = lrc.split("\n");
  let lrcObj = {};
  for (let i = 0; i < lyrics.length; i++) {
    let lyric = lyrics[i];
    let timeReg = /\[\d*:\d*((\.|\:)\d*)*\]/g;
    let timeRegExpArr = lyric.match(timeReg);
    if (!timeRegExpArr) continue;
    let clause = lyric.replace(timeReg, '');
    for (let k = 0, h = timeRegExpArr.length; k < h; k++) {
      let t = timeRegExpArr[k];
      let min = Number(String(t.match(/\[\d*/i)).slice(1));
      let sec = Number(String(t.match(/\:\d*/i)).slice(1));
      let time = min * 60 + sec;
      lrcObj[time] = clause;
    }
  }
  return lrcObj;
}

module.exports = {
  get,
  parse
}